package institution

import (
	"context"
	"errors"
	"feng-che.com/server/driver-quiz/internal/dep_db"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongoDB"
)

// School 驾校
type School struct {
	mongoDB.MongoDefaultModelNonID `bson:"basic"`
	ID                             primitive.ObjectID   `bson:"_id,omitempty" json:"id"`
	Name                           string               `bson:"name" json:"name"`
	Address                        string               `bson:"address" json:"address"`
	Lat                            float64              `bson:"lat" json:"lat"`
	Lng                            float64              `bson:"lng" json:"lng"`
	Logo                           string               `bson:"logo" json:"logo"`
	Photos                         []string             `bson:"photos" json:"photos"`
	Introduce                      string               `bson:"introduce" json:"introduce"`
	Phone                          string               `bson:"phone" json:"phone"`
	Coaches                        []primitive.ObjectID `bson:"coaches" json:"coaches"` // 教练
}

func (s *School) Save(ctx context.Context, updateOptions ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
	if s.ID.IsZero() {
		s.ID = primitive.NewObjectID()
	}
	var opts []*options.UpdateOptions
	if len(updateOptions) > 0 && updateOptions[0] != nil {
		opts = updateOptions
	} else {
		opts = append(opts, options.Update().SetUpsert(true))
	}
	result, err := s.GetCollection().UpdateByID(ctx, s.ID, bson.D{
		{"$set", s},
	}, opts...)
	return result, err
}

func (s *School) Update(ctx context.Context, dataFields *bson.D, opts ...*options.UpdateOptions) error {
	if s.ID.IsZero() {
		return errors.New("没有带入id")
	}
	*dataFields = append(*dataFields, bson.E{Key: "$set", Value: bson.D{*mongoDB.CommonUpdateTimeFieldWithCurrentTime()}})
	_, err := s.GetCollection().UpdateByID(ctx, s.ID, *dataFields, opts...)
	return err
}

func (s *School) Delete(ctx context.Context) error {
	if s.ID.IsZero() {
		return errors.New("没有带入id")
	}
	delFiled := bson.D{}
	fields := mongoDB.CommonDeleteWriteFields()
	for _, i2 := range *fields {
		delFiled = append(delFiled, i2)
	}
	return s.Update(ctx, &bson.D{
		{"$set", delFiled},
	})
}

func (s *School) GetCollectionName() string {
	return "school"
}

func (s *School) GetCollection() *mongo.Collection {
	name := s.GetCollectionName()
	return dep_db.ObjectCollection(&name)
}

func (s *School) Create() {
	s.MongoDefaultModelNonID.Create()
	s.Coaches = make([]primitive.ObjectID, 0)
	s.Photos = make([]string, 0)
	s.ID = primitive.NewObjectID()
	return
}
